<?php

namespace App\Supports\Payment\Methods\Balance;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodRefund;

class RefundOrder extends Method implements MethodRefund
{
	public function validate($order = null)
	{
		if (! $order->isPaid()) {
			abort(403, '目标订单未支付');
		}
		if ($order->paid_method !== 'balance') {
			abort(403, '目标订单不能通过账户余额退款');
		}
		/*if ($order->refunds()->first()->refund_status !== 'confirmed') {
			abort(403, '目标售后未审核');
		}*/
	}

	public function info($order = null) {}

	public function refund($order = null)
	{
		$this->validate($order);

		DB::transaction(function () use ($order) {

			$order->refunds()->first()->update(['refund_status' => 'succeeded']);


			$orderData['has_refund'] = true;
			
			$order->update($orderData);

            $money = $order->refunds()->first()->refund_money;
            $data = ['order_refund_id' => $order->refunds()->first()->id];
			account_balances($order->user)->plusOrderRefund($money, $data);
			//event(new OrderRefundedEvent($refund));
		});
	}
}
